package lv.solcraft.replication.server.rest;

import lv.solcraft.replication.server.boot.Booter;
import lv.solcraft.replication.server.boot.StartupOptions;
import lv.solcraft.replication.server.rest.restlets.ListServersRestlet;
import lv.solcraft.replication.server.rest.restlets.RestartServerRestlet;
import lv.solcraft.replication.server.rest.restlets.StopServerRestlet;

import org.apache.log4j.Logger;
import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Directory;
import org.restlet.Restlet;
import org.restlet.Router;

public class ReplicationServerApplication extends Application {

    private static final Logger log = Logger.getLogger(ReplicationServerApplication.class);
    private Booter booter;

    public ReplicationServerApplication(Context context, StartupOptions startupOptions) {
        super(context);
        booter = new Booter(startupOptions);
        try {
            booter.start();
        } catch (Exception e) {
            log.error("Replication server startup failed, " + e.getMessage(), e);
        }
    }

    @Override
    public Restlet createRoot() {
        Router router = new Router();
        attachWebUiDirectoryRestlet(router);
        attach(router, "/server/stop", new StopServerRestlet(getContext()));
        attach(router, "/server/restart", new RestartServerRestlet(getContext()));
        for (String serverName : booter.getServers()) {
            attach(router, "/api/servers/" + serverName, new ServerApplication(getContext(), booter
                    .getServer(serverName)));
        }
        attach(router, "/api/servers-list", new ListServersRestlet(getContext(), booter));
        return router;
    }

    protected void attach(Router router, String pattern, Restlet restlet) {
        ErrorFilter errorFilter = new ErrorFilter();
        errorFilter.setNext(restlet);
        router.attach(pattern, errorFilter);
    }

    @Override
    public void stop() throws Exception {
        log.info("Stopping replication server");
        if (booter != null)
            booter.stop();
        super.stop();
        log.info("Stopped replication server");
    }

    @Override
    public void start() throws Exception {
        log.info("Starting replication server");
        super.start();
        log.info("Started replication server");
    }

    private void attachWebUiDirectoryRestlet(Router router) {
        Directory directory = new Directory(getContext(), "file:///C:/work/replication4/server/webui");
        directory.setModifiable(true);
        directory.setListingAllowed(true);
        router.attach("/webui", directory);
    }

}
